﻿using AdminStyem.Application.Command.traceabilityCommand;
using AdminStyem.Application.DTO;
using AdminStyem.Domain.Entity;
using AdminStyem.Repositories;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdminStyem.Application.CommandHandler.traceabilityCommandHandler
{
    public class TraceabilityShowCommandHandler : IRequestHandler<TraceabilityShowCommand, APIResult<APiPaging<TrcatebilityCommodityDTO>>>
    {
        IBaseRespository<Traceability> BaseTraceability;
        IBaseRespository<Commodity> BaseCommodity;

        public TraceabilityShowCommandHandler(IBaseRespository<Commodity> baseCommodity, IBaseRespository<Traceability> BaseTraceability)
        {
            BaseCommodity = baseCommodity;
            this.BaseTraceability = BaseTraceability;
        }

        public async Task<APIResult<APiPaging<TrcatebilityCommodityDTO>>> Handle(TraceabilityShowCommand request, CancellationToken cancellationToken)
        {
            APIResult<APiPaging<TrcatebilityCommodityDTO>> ret = new APIResult<APiPaging<TrcatebilityCommodityDTO>>();
            ret.Code = ResultCode.查询成功;
            ret.Message = ResultCode.查询成功.ToString();
            
            var list= from a in await BaseTraceability.GetAll()
                      join b in await BaseCommodity.GetAll() on a.CommodityId equals b.CommodityId
                      where a.IsDeleted == false
                      select new TrcatebilityCommodityDTO
                      {
                          CommodityName = b.CommodityName,
                          CommodityId = a.CommodityId,
                          TraceabilityId = a.TraceabilityId,
                          TraceabilityBatch = a.TraceabilityBatch,
                          TraceabilityPhoto = a.TraceabilityPhoto,
                          TraceabilityShelf = a.TraceabilityShelf,
                          TraceaDocuments = a.TraceaDocuments,
                          Manufacturers = a.Manufacturers   
                      };
            int totalCount = list.Count();
            int totalPage = (int)Math.Ceiling(totalCount / request.PageSize * 1.0);
            list = list.OrderBy(x=>x.TraceabilityId).Skip((request.PageIndex - 1)*request.PageSize).Take(request.PageSize);
            APiPaging<TrcatebilityCommodityDTO> paging = new APiPaging<TrcatebilityCommodityDTO>();
            paging.TotalCount=totalCount;
            paging.TotalPage=totalPage;
            paging.list = list.ToList();
           ret.Data = paging;
            return ret;
        }
    }
}
